package cn.iocoder.yudao.module.system.controller.admin.tenant;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.account.TenantAccountRespVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.account.TenantAccountSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.admin.AdminBuyTenantBillReqVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.admin.AdminBuyUserBillReqVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.product.TenantProductSumRespVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.*;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantAccountDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import cn.iocoder.yudao.module.system.enums.product.ProductEnum;
import cn.iocoder.yudao.module.system.service.oauth2.OAuth2TokenService;
import cn.iocoder.yudao.module.system.service.tenant.*;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

@Tag(name = "管理后台 - 租户")
@RestController
@RequestMapping("/system/tenant")
@Slf4j
public class TenantController {

    @Resource
    private TenantService tenantService;

    @Resource
    private TenantProductService tenantProductService;
    @Resource
    private TenantCallChannelService tenantCallChannelService;

    @Resource
    private TenantCallNumberService tenantCallNumberService;

    @Resource
    private OAuth2TokenService oauth2TokenService;

    @GetMapping("/get-id-by-name")
    @PermitAll
    @Operation(summary = "使用租户名，获得租户编号", description = "登录界面，根据用户的租户名，获得租户编号")
    @Parameter(name = "name", description = "租户名", required = true, example = "1024")
    public CommonResult<TenantDO> getTenantIdByName(@RequestParam("name") String name) {
        TenantDO tenant = tenantService.getTenantByName(name);
        return success(tenant);
    }

    @GetMapping("/get-by-website")
    @PermitAll
    @Operation(summary = "使用域名，获得租户信息", description = "登录界面，根据用户的域名，获得租户信息")
    @Parameter(name = "website", description = "域名", required = true, example = "www.iocoder.cn")
    public CommonResult<TenantSimpleRespVO> getTenantByWebsite(@RequestParam("website") String website) {
        TenantDO tenant = tenantService.getTenantByWebsite(website);
        return success(BeanUtils.toBean(tenant, TenantSimpleRespVO.class));
    }

    @PostMapping("/create")
    @Operation(summary = "创建租户")
    @PreAuthorize("@ss.hasPermission('system:tenant:create')")
    public CommonResult<Long> createTenant(@Valid @RequestBody TenantSaveReqVO createReqVO) {
        return success(tenantService.createTenant(createReqVO).get("tenantId"));
    }

    @PutMapping("/update")
    @Operation(summary = "更新租户")
    @PreAuthorize("@ss.hasPermission('system:tenant:update')")
    public CommonResult<Boolean> updateTenant(@Valid @RequestBody TenantSaveReqVO updateReqVO) {
        tenantService.updateTenant(updateReqVO);
        return success(true);
    }

    @PutMapping("/corp-auth")
    @Operation(summary = "企业认证")
    public CommonResult<Boolean> updateTenantCorpAuth(@Valid @RequestBody TenantAuthUpdateReqVO updateReqVO) {
        tenantService.updateTenantCorpAuth(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除租户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant:delete')")
    public CommonResult<Boolean> deleteTenant(@RequestParam("id") Long id) {
        tenantService.deleteTenant(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得租户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<TenantRespVO> getTenant(@RequestParam("id") Long id) {
        TenantDO tenant = tenantService.getTenant(id);
        TenantRespVO bean = BeanUtils.toBean(tenant, TenantRespVO.class);
        bean.setChannelIdList(tenantCallChannelService.getCallChannelIdList(id));
        bean.setNumberIdList(tenantCallNumberService.getCallNumberIdList(id));

        return success(bean);
    }

    @GetMapping("/simple-info")
    @Operation(summary = "获得租户简要信息")
    public CommonResult<TenantRespVO> getTenantSimpleInfo() {
        TenantDO tenant = tenantService.getTenant(TenantContextHolder.getTenantId());
        TenantRespVO bean = BeanUtils.toBean(tenant, TenantRespVO.class);
        return success(bean);
    }

    @GetMapping("/get-proxy-manager-list")
    @Operation(summary = "获取代理商列表")
    public CommonResult<List<TenantRespVO>> getProxyManagerList() {
        List<TenantDO> tenant = tenantService.getProxyManagerList();
        return success(BeanUtils.toBean(tenant, TenantRespVO.class));
    }

    @GetMapping("/jump-login")
    @Operation(summary = "跳转到指定租户账户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<AuthLoginRespVO> jumpTenantAccount(@RequestParam("id") Long id) {
        TenantDO tenant = tenantService.getTenant(id);
        // 创建访问令牌
        return TenantUtils.execute(id, () -> {
            OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(tenant.getContactUserId(), UserTypeEnum.ADMIN.getValue(), OAuth2ClientConstants.CLIENT_ID_DEFAULT, null);
            // 构建返回结果(这块代码的应用，乱七八糟的， 反正写法好多种， 主打一个能用就行吧 -------)
            AuthLoginRespVO convert = AuthConvert.INSTANCE.convert(accessTokenDO);
            convert.setTenantId(id);
            return success(convert);
        });
    }

    @GetMapping("/page")
    @Operation(summary = "获得租户分页")
    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<PageResult<TenantRespVO>> getTenantPage(@Valid TenantPageReqVO pageVO) {
        PageResult<TenantDO> pageResult = tenantService.getTenantPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }
        return success(new PageResult<>(buildTenantList(pageResult.getList()), pageResult.getTotal()));
    }

    public List<TenantRespVO> buildTenantList(List<TenantDO> list) {
        if (CollUtil.isEmpty(list)) {
            return java.util.Collections.emptyList();
        }
        Map<Long, List<TenantProductSumRespVO>> tenantProductMap = tenantProductService.getRemainNumMapByTenantId(convertSet(list, TenantDO::getId));

        return BeanUtils.toBean(list, TenantRespVO.class, tenantVO -> {
            tenantVO.setTenantProduct(tenantProductMap.get(tenantVO.getId()));
        });
    }


    @GetMapping("/simple-list")
    @Operation(summary = "获得租户列表")
    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<List<TenantRespVO>> getTenantPage() {
        @Valid TenantPageReqVO pageVO = new TenantPageReqVO();
        pageVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        pageVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        List<TenantDO> pageResult = tenantService.getTenantPage(pageVO).getList();
        return success(BeanUtils.toBean(pageResult, TenantRespVO.class));
    }


    @GetMapping("/sub-customer-page")
    @Operation(summary = "获得下級租户分页")
//    @PreAuthorize("@ss.hasPermission('system:tenant:query')")
    public CommonResult<PageResult<TenantRespVO>> subCustomerPage(@Valid TenantPageReqVO pageVO) {
        pageVO.setParentId(TenantContextHolder.getTenantId());
        PageResult<TenantDO> pageResult = tenantService.getTenantPage(pageVO);
        return success(BeanUtils.toBean(pageResult, TenantRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出租户 Excel")
    @PreAuthorize("@ss.hasPermission('system:tenant:export')")
    @OperateLog(type = EXPORT)
    public void exportTenantExcel(@Valid TenantPageReqVO exportReqVO,
                                  HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TenantDO> list = tenantService.getTenantPage(exportReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "租户.xls", "数据", TenantRespVO.class,
                BeanUtils.toBean(list, TenantRespVO.class));
    }

    @GetMapping("/get-by-sign")
    @Operation(summary = "使用签名，获得租户信息", description = "AI外呼系统sign对接，获得租户信息")
    @Parameter(name = "sign")
    @PermitAll
    public CommonResult<Map<String, Object>> getTenant(@RequestParam("sign") String sign) {
        TenantDO tenant = tenantService.getTenantBySign(sign);
        if (Objects.isNull(tenant)) {
            return error(100500, "账户不存在");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("detail", tenant);
        result.put("robotNum", tenantService.getTenantProductBalance(ProductEnum.ROBOT_NUM.getCode(), tenant.getId()));
        result.put("robotCall", tenantService.getTenantProductBalance(ProductEnum.ROBOT_CALL.getCode(), tenant.getId()));
        return success(result);
    }

    @PostMapping("/buy-user-bill")
    @Operation(summary = "购买用户话费套餐")
    @PreAuthorize("@ss.hasPermission('system:tenant:update')")
    public CommonResult<Boolean> buyUserBillByAdmin(@Valid @RequestBody AdminBuyUserBillReqVO reqVO) {
        tenantService.buyUserBill(reqVO);

        return success(Boolean.TRUE);
    }

    @PostMapping("/buy-tenant-bill")
    @Operation(summary = "购买企业话费套餐：主要是群呼话费")
    @PreAuthorize("@ss.hasPermission('system:tenant:update')")
    public CommonResult<Boolean> buyTenantBillByAdmin(@Valid @RequestBody AdminBuyTenantBillReqVO reqVO) {
        tenantService.buyTenantBill(reqVO);
        return success(Boolean.TRUE);
    }


    @GetMapping("/get-proxy-main-page-data")
    @Operation(summary = "获取代理商主页统计数据")
    public CommonResult<TenantProxyMainPageRespVO> getProxyMainPageData() {
        return success(tenantService.getTenantProxyMainPage());
    }


    @GetMapping("/get-proxy-customer-list")
    @Operation(summary = "获取代理客户列表")
    public CommonResult<List<TenantRespVO>> getProxyCustomerList() {
        TenantPageReqVO reqVO = new TenantPageReqVO();
        reqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        reqVO.setParentId(TenantContextHolder.getTenantId());
        List<TenantDO> pageResult = tenantService.getTenantPage(reqVO).getList();
        return success(BeanUtils.toBean(pageResult, TenantRespVO.class));
    }
}
